import urllib2, urllib,re, cookielib, time, threading

global browser
global domain

domain="http://watchseries.eu"
cj=cookielib.CookieJar()
cj.clear()
CHandler = urllib2.HTTPCookieProcessor(cj)
browser = urllib2.build_opener(CHandler)
browser.addheaders = [('User-agent', 'Mozilla/5.0')]
urllib2.install_opener(browser)

def id2flv(id):
	browser = urllib2.build_opener()
	urllib2.install_opener(browser)
	data=urllib.urlencode({"op":"download1","method_free":"Free Download","id":id})
	url="http://gorillavid.in/"+id
	req = urllib2.Request(url)
	res = browser.open(req, data)
	res =res.read()
	f = re.findall('file:\s"(.*?)"', res)
	return list(set(f))[0]

def trimmer(strng):
	return strng.replace("&nbsp;"," ")

class watchserieseu():
	def __init__(self):
		self.letters=["09","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
		self.series={}
		threads=[]
		for letter in self.letters:
			tr=threading.Thread(target=self.__parse_serie_letter,args=(letter,))
			tr.start()
			threads.append(tr)
		## wait until all threads ends consider exceptions alter! it is important because it will lock class
		while len(set(threads)-set(threading.enumerate()))!=len(threads):
			continue

	def __parse_serie_letter(self,letter):
		global browser
		global domain
		req=urllib2.Request(domain + "/letters/" + letter)
		res=browser.open(req)
		res=res.read()
		series=re.findall('<li><a href="(.*?)" title="(.*?)">.*?<span class="epnum">(.*?)</span>',res)
		for ser in series:
			if len(ser) == 3 :
				s_ob=self.__serie(ser[1],ser[0],ser[2])
				self.series[ser[1]]=s_ob
		return


	class __serie():
		def __init__(self,name,link,episodes):
			self.name=name
			self.link=link
			self.seasons=[]
			self.lasttime=-1

		def __parse_seasons(self):
			global browser
			global domain
			self.seasons=[]
			req=req=urllib2.Request(self.link)
			res=browser.open(req)
			seas=re.findall('<h2 class="lists"><a href=.*?">(.*?)\s\s\(.*?<ul class="listings">(.*?)</ul>',res.read(),re.DOTALL)
			i=1
			for sea in seas:
				epis=re.findall('<li><a href="(.*?)"><span class="">(.*?)</span><span class="epnum">(.*?)</span></a></li>',sea[1])
				season_ob=self.__season(i)
				self.seasons.append(season_ob)
				for epi in epis:
					link= domain + epi[0][2:]
					episode_obj=self.__episode(trimmer(epi[1]),link,epi[2])
					season_ob.episodes.append(episode_obj)
				i+=1
			self.lasttime=time.time()
			return

		def get_seasons(self):
			if time.time()-self.lasttime > 5*60*1000 :
				self.__parse_seasons()
			return self.seasons

		class __episode():
			def __init__(self,name,link,date):
				self.name=name
				self.link=link
				self.date=date
				self.lasttime=-1
				self.videos=[]
				
			def get_videos(self):
				if time.time()-self.lasttime > 5*60*1000 :
					self.videos=[]
					grs=self.__filter_gorillas()
					#print grs
					threads=[]
					for gr in grs:
						tr=threading.Thread(target=self.__parse_vid_pagelink,args=(gr,))
						tr.start()
						threads.append(tr)
					while len(set(threads)-set(threading.enumerate()))!=len(threads):
						continue
					self.lasttime=time.time()
				return self.videos

			def __parse_vid_pagelink(self,link):
				global browser
				global domain
				req = urllib2.Request(link)
				res = browser.open(req)
				res = res.read()
				f = re.findall('"'+domain+'/gateway.php?(.*?)"', res)
				link2=domain+"/gateway.php"+f[0]
				req = urllib2.Request(link2)
				req.add_header('Referer',link)
				res=urllib2.urlopen(req)
				self.videos.append(id2flv(res.geturl().split("/")[-1]))
				return

			def __filter_gorillas(self):
				global browser
				req= urllib2.Request(self.link)
				res = browser.open(req)
				f = re.findall('<div\sclass="site">.*?gorillavid.in.*?<a href="../(.*?)"', res.read(),re.DOTALL)
				return [domain + "/" + x for x in  f]

		class __season():
			def __init__(self, number):
				self.number=number
				self.episodes=[]
			
			def get_episodes(self):
				return self.episodes


	def get_serie_names(self):
		return self.series.keys()

	def get_serie(self,key):
		return self.series[key]